package com.gsta.ifishery.netty.handler;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 报文解析处理 . <br>
 * 
 * @author hkb
 */
public class MessageParsingHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 解析次数
     */
    private int analyticTimes;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        StringBuilder sb = null;
        Map<String, Object> result = null;
        try {
            // 报文解析处理
            sb = new StringBuilder();
            result = JSON.parseObject(msg);

            sb.append(result);
            sb.append("\n");
            msg = sb.toString();
            // ctx.writeAndFlush(sb);
        } catch (JSONException e) {
            analyticTimes++;
            if (analyticTimes > 1) {
                // 报文连续无法解析
                String errorCode = "-1\n";
                ctx.writeAndFlush(errorCode);
            }
            log.error("报文解析失败: " + e.getMessage());
        }
        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        ctx.close();
    }

}
